/**
 * 层序遍历，遍历每层的每个节点时候交换左右节点
 * @param {TreeNode} root
 * @return {TreeNode}
 */

const reverse = (node) => {
  const temp = node.left
  node.left = node.right
  node.right = temp
}

const invertTree = root => {
  if (!root) return root
  const queue = [root]
  while (queue.length) {
    const len = queue.length

    for (let i = 0; i < len; i++) {
      const node = queue.shift()
      reverse(node, node.left, node.right)
      node.left && queue.push(node.left)
      node.right && queue.push(node.right)
    }
  }
  return root
}

const root = {
  val: 1,
  left: {
    val: 2,
    left: null,
    right: null
  },
  right: {
    val: 3,
    left: null,
    right: null
  }
}

console.log(invertTree(root))